<template>
  <div class="profile-app">
    <!-- Header -->
    <AppHeader 
      :current-user="currentUser"
      :show-search="false"
      @login="showLoginModal"
      @register="showRegisterModal"
      @logout="handleLogout"
    />

    <!-- Breadcrumb Navigation -->
    <nav class="breadcrumb-nav">
      <div class="breadcrumb-content">
        <div class="breadcrumb">
          <router-link to="/" class="breadcrumb-item">
            <i class="fas fa-home"></i>
            笔记中心
          </router-link>
          <span class="breadcrumb-item">个人中心</span>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
      <div class="profile-container">
        <!-- Profile Header -->
        <div class="profile-header">
          <div class="profile-avatar">
            <img v-if="currentUser?.avatar" :src="getAvatarUrl(currentUser.avatar)" :alt="currentUser?.name" class="avatar-image">
            <i v-else class="fas fa-user-circle"></i>
          </div>
          <div class="profile-info">
            <h1>{{ currentUser?.name || '访客' }}</h1>
            <p>{{ currentUser?.email || '未登录' }}</p>
          </div>
        </div>

        <!-- Profile Sections -->
        <div class="profile-sections">
          <!-- Recent Activity -->
          <section class="profile-section">
            <h3>最近活动</h3>
            <div class="activity-list">
              <div 
                v-for="activity in recentActivities" 
                :key="activity.id"
                class="activity-item"
              >
                <div class="activity-icon">
                  <i :class="activity.icon"></i>
                </div>
                <div class="activity-content">
                  <div class="activity-text">{{ activity.text }}</div>
                  <div class="activity-time">{{ formatDate(activity.date) }}</div>
                </div>
              </div>
              <div v-if="recentActivities.length === 0" class="empty-activity">
                <i class="fas fa-clock"></i>
                <span>暂无活动记录</span>
              </div>
            </div>
          </section>

          <!-- Account Settings -->
          <section class="profile-section">
            <h3>账户设置</h3>
            <div class="settings-list">
              <div class="setting-item">
                <div class="setting-info">
                  <h4>个人信息</h4>
                  <p>更新您的姓名和邮箱地址</p>
                </div>
                <button class="btn btn-outline" @click="editProfile">
                  <i class="fas fa-edit"></i>
                  编辑
                </button>
              </div>
              <!-- 只有管理员用户才能看到清空数据功能 -->
              <div class="setting-item" v-if="isUserAdmin()">
                <div class="setting-info">
                  <h4>清空数据</h4>
                  <p>删除所有笔记、视频和任务</p>
                </div>
                <button class="btn btn-danger" @click="clearAllData">
                  <i class="fas fa-trash"></i>
                  清空
                </button>
              </div>
            </div>
          </section>
        </div>
      </div>
    </main>
    
    <!-- Edit Profile Modal -->
    <div class="modal" v-if="showEditProfileModal" @click="handleModalOverlayClick">
      <div class="modal-content">
        <div class="modal-header">
          <h3>编辑个人信息</h3>
          <button class="modal-close" @click="hideEditProfileModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group avatar-upload-group">
            <label>头像</label>
            <div class="avatar-upload-container">
              <div class="avatar-preview">
                <img v-if="editingProfile.avatarPreview" :src="editingProfile.avatarPreview" alt="头像预览" class="avatar-preview-image">
                <i v-else class="fas fa-user-circle avatar-placeholder"></i>
              </div>
              <div class="avatar-upload-controls">
                <input 
                  type="file" 
                  ref="avatarInput"
                  accept="image/*"
                  @change="handleAvatarChange"
                  class="avatar-file-input"
                >
                <button class="btn btn-outline" @click="triggerAvatarUpload">
                  <i class="fas fa-upload"></i>
                  上传头像
                </button>
                <button 
                  v-if="editingProfile.avatarPreview" 
                  class="btn btn-ghost" 
                  @click="removeAvatar"
                >
                  <i class="fas fa-trash"></i>
                  删除
                </button>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label for="profileName">姓名</label>
            <input 
              type="text" 
              id="profileName" 
              v-model="editingProfile.name"
              placeholder="输入您的姓名..."
            >
          </div>
          <div class="form-group">
            <label for="profileEmail">邮箱</label>
            <input 
              type="email" 
              id="profileEmail" 
              v-model="editingProfile.email"
              placeholder="输入您的邮箱..."
              disabled
            >
            <p class="form-help-text">邮箱地址不可更改</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-ghost" @click="hideEditProfileModal">取消</button>
          <button class="btn btn-primary" @click="saveProfile">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AppHeader from '@/components/AppHeader.vue'
import apiService from '@/services/api.js'

export default {
  name: 'ProfilePage',
  components: {
    AppHeader
  },
  data() {
    return {
      currentUser: null,
      courses: [],
      videoCourses: [],
      tasks: [],
      stats: {
        courses: 0,
        videoCourses: 0,
        tasks: 0,
        battlePower: 0,
        recentLogs: [] // 添加操作日志数据
      },
      // 个人信息编辑相关数据
      showEditProfileModal: false,
      editingProfile: {
        name: '',
        email: '',
        avatar: '', // 存储头像URL
        avatarPreview: '', // 存储头像预览URL
        avatarFile: null // 存储头像文件对象
      }
    }
  },
  computed: {
    userStats() {
      return this.stats
    },
    recentActivities() {
      const activities = []
      
      // 添加现有的活动
      // Add course activities
      this.courses.forEach(course => {
        activities.push({
          id: 'course_' + course.id,
          icon: 'fas fa-book',
          text: `创建了笔记"${course.name}"`,
          date: course.createdAt
        })
        
        if (course.lastModified && course.lastModified !== course.createdAt) {
          activities.push({
            id: 'course_edit_' + course.id,
            icon: 'fas fa-edit',
            text: `更新了笔记"${course.name}"`,
            date: course.lastModified
          })
        }
      })
      
      // Add video course activities
      this.videoCourses.forEach(course => {
        activities.push({
          id: 'video_' + course.id,
          icon: 'fas fa-video',
          text: `创建了视频课程"${course.name}"`,
          date: course.createdAt
        })
      })
      
      // Add task activities
      this.tasks.filter(task => task.status === 'completed').forEach(task => {
        activities.push({
          id: 'task_' + task.id,
          icon: 'fas fa-check',
          text: `完成了任务"${task.title}"`,
          date: task.createdAt
        })
      })
      
      // 添加操作日志作为活动
      if (this.stats.recentLogs && Array.isArray(this.stats.recentLogs)) {
        this.stats.recentLogs.forEach(log => {
          activities.push({
            id: 'log_' + log.id,
            icon: this.getActionIcon(log.action),
            text: log.description || this.formatActionText(log.action, log.resourceType),
            date: log.createdAt
          })
        })
      }
      
      // Sort by date and return last 10
      return activities
        .sort((a, b) => new Date(b.date) - new Date(a.date))
        .slice(0, 10)
    }
  },
  mounted() {
    this.loadData()
    this.loadUserLogs()
    this.checkAuthStatus()
  },
  methods: {
    // 添加获取头像URL的方法，处理相对路径和绝对路径
    getAvatarUrl(avatarPath) {
      if (!avatarPath) return '';
      
      // 如果是相对路径，使用代理访问
      if (avatarPath.startsWith('/uploads/')) {
        return avatarPath;
      }
      
      // 如果是完整的本地URL，转换为相对路径以使用代理
      if (avatarPath.startsWith('http://localhost:3000/uploads/')) {
        return avatarPath.replace('http://localhost:3000', '');
      }
      
      // 如果是绝对路径，保持原样（可能用于外部头像）
      if (avatarPath.startsWith('http')) {
        return avatarPath;
      }
      
      // 其他情况，添加相对路径前缀
      return `/uploads/images/${avatarPath}`;
    },
    
    // 添加管理员判断方法
    isUserAdmin() {
      // 检查 currentUser 是否存在且具有 role 属性
      if (this.currentUser && this.currentUser.role) {
        return this.currentUser.role === 'admin'
      }
      // 默认情况下，只有"系统管理员"用户是管理员
      return this.currentUser && this.currentUser.name === '系统管理员'
    },
    
    async loadData() {
      if (!this.currentUser) {
        return
      }
      
      try {
        // Load user stats
        const statsResponse = await apiService.getUserStats()
        // 修复：apiService.getUserStats() 已经返回了解包后的数据，不需要再访问 .data
        if (statsResponse && typeof statsResponse === 'object') {
          this.stats = statsResponse
        }
        
        // Load courses
        const courseResponse = await apiService.getCourses()
        this.courses = courseResponse.courses || []
        
        // Load video courses
        const videoCourseResponse = await apiService.getVideoCourses()
        this.videoCourses = videoCourseResponse.courses || []
        
        // Load tasks
        const taskResponse = await apiService.getTasks()
        this.tasks = taskResponse.tasks || []
      } catch (error) {
        console.error('加载用户数据失败:', error)
        // Fallback to localStorage if API fails
        this.courses = JSON.parse(localStorage.getItem('courses')) || []
        this.videoCourses = JSON.parse(localStorage.getItem('videoCourses')) || []
        this.tasks = JSON.parse(localStorage.getItem('userTasks')) || []
      }
    },
    async loadUserLogs() {
      try {
        // Load user logs
        this.stats.recentLogs = await apiService.getUserLogs()
      } catch (error) {
        console.error('加载用户日志失败:', error)
        this.stats.recentLogs = []
      }
    },
    async checkAuthStatus() {
      const savedUser = localStorage.getItem('currentUser')
      const savedToken = localStorage.getItem('auth_token')
      
      if (savedUser && savedToken) {
        this.currentUser = JSON.parse(savedUser)
        // Refresh user data from server
        try {
          const userData = await apiService.getCurrentUser()
          // 根据API服务的实现，userData已经是解包后的用户数据 {id, name, email, ...}
          if (userData && userData.id) {
            this.currentUser = userData
            localStorage.setItem('currentUser', JSON.stringify(userData))
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
        }
      }
    },
    calculateBattlePower() {
      return this.stats.battlePower
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const now = new Date()
      const diffTime = Math.abs(now - date)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 1) {
        return '今天'
      } else if (diffDays === 2) {
        return '昨天'
      } else if (diffDays <= 7) {
        return `${diffDays} 天前`
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    },
    async editProfile() {
      // 初始化编辑数据
      this.editingProfile = {
        name: this.currentUser?.name || '',
        email: this.currentUser?.email || '',
        avatar: this.currentUser?.avatar || '',
        avatarPreview: this.getAvatarUrl(this.currentUser?.avatar) || '',
        avatarFile: null
      }
      this.showEditProfileModal = true
    },
    hideEditProfileModal() {
      this.showEditProfileModal = false
    },
    handleModalOverlayClick(e) {
      if (e.target.classList.contains('modal')) {
        this.hideEditProfileModal()
        this.hideCourseModal()
        this.hideEditCourseModal()
        this.hideChapterModal()
      }
    },
    triggerAvatarUpload() {
      // 触发文件选择
      this.$refs.avatarInput.click()
    },
    handleAvatarChange(e) {
      const file = e.target.files[0]
      if (file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
          this.$toast('请选择图片文件', {
            title: '文件类型错误',
            variant: 'error'
          })
          return
        }
        
        // 检查文件大小（限制为5MB）
        if (file.size > 5 * 1024 * 1024) {
          this.$toast('头像文件大小不能超过5MB', {
            title: '文件过大',
            variant: 'error'
          })
          return
        }
        
        // 保存文件对象
        this.editingProfile.avatarFile = file
        
        // 创建预览URL
        this.editingProfile.avatarPreview = URL.createObjectURL(file)
      }
    },
    removeAvatar() {
      // 清除头像
      this.editingProfile.avatarPreview = ''
      this.editingProfile.avatarFile = null
      this.$refs.avatarInput.value = ''
    },
    async saveProfile() {
      if (!this.editingProfile.name?.trim()) {
        await this.$alert('请输入姓名', {
          title: '输入错误',
          variant: 'warning'
        })
        return
      }
      
      try {
        let avatarUrl = this.currentUser?.avatar || ''
        
        // 如果有新的头像文件，先上传头像
        if (this.editingProfile.avatarFile) {
          const formData = new FormData()
          formData.append('avatar', this.editingProfile.avatarFile)
          
          const uploadResponse = await apiService.uploadAvatar(formData)
          if (uploadResponse.success && uploadResponse.data) {
            avatarUrl = uploadResponse.data.url
          }
        } else if (this.editingProfile.avatarPreview === '') {
          // 如果用户删除了头像，则设置为空
          avatarUrl = ''
        }
        
        const userData = {
          name: this.editingProfile.name.trim(),
          avatar: avatarUrl
          // 注意：邮箱地址不可更改，所以不传递
        }
        
        const updatedUser = await apiService.updateProfile(userData)
        
        // 更新当前用户信息
        // 修正访问路径：API服务已经解包了响应数据，直接使用返回的用户对象
        this.currentUser = {
          ...this.currentUser,
          name: updatedUser.name,
          avatar: updatedUser.avatar
        }
        
        // 更新本地存储
        localStorage.setItem('currentUser', JSON.stringify(this.currentUser))
        
        // 隐藏模态框
        this.hideEditProfileModal()
        
        await this.$toast('个人信息更新成功！', {
          title: '更新成功',
          variant: 'success'
        })
      } catch (error) {
        console.error('更新个人信息失败:', error)
        await this.$toast('更新个人信息失败: ' + (error.message || '未知错误'), {
          title: '更新失败',
          variant: 'error'
        })
      }
    },
    async clearAllData() {
      // 检查用户是否为管理员
      const isAdmin = this.currentUser && 
        (this.currentUser.role === 'admin' || this.currentUser.name === '系统管理员');
      
      if (!isAdmin) {
        await this.$toast('只有管理员用户才能执行此操作', {
          title: '权限不足',
          variant: 'error'
        });
        return;
      }
      
      const firstConfirm = await this.$confirm('确定要清空所有数据吗？此操作不可恢复！', {
        title: '清空数据',
        variant: 'error',
        confirmText: '继续'
      });
      
      if (firstConfirm) {
        const secondConfirm = await this.$confirm('这将删除所有用户创建的笔记、视频课程和任务，请再次确认！', {
          title: '最后确认',
          variant: 'error',
          confirmText: '确认删除'
        });
        
        if (secondConfirm) {
          // 使用新的API接口清空所有数据
          try {
            const response = await apiService.clearAllData();
            
            if (response.success) {
              // 重新加载数据
              await this.loadData();
              
              await this.$toast('所有数据已清空', {
                title: '操作成功',
                variant: 'success'
              });
            } else {
              throw new Error(response.message || '清空数据失败');
            }
          } catch (error) {
            console.error('清空数据失败:', error);
            await this.$toast('清空数据失败: ' + (error.message || '未知错误'), {
              title: '操作失败',
              variant: 'error'
            });
          }
        }
      }
    },
    showLoginModal() {
      // Handle login modal
    },
    showRegisterModal() {
      // Handle register modal
    },
    async handleLogout() {
      try {
        await apiService.logout()
      } catch (error) {
        console.error('注销失败:', error)
      } finally {
        this.currentUser = null
        this.$router.push('/')
      }
    },
    // 添加获取操作图标的方法
    getActionIcon(action) {
      const iconMap = {
        'create': 'fas fa-plus',
        'update': 'fas fa-edit',
        'delete': 'fas fa-trash',
        'login': 'fas fa-sign-in-alt',
        'logout': 'fas fa-sign-out-alt',
        'view': 'fas fa-eye',
        'export': 'fas fa-download',
        'import': 'fas fa-upload',
        'clear': 'fas fa-trash-alt'
      }
      return iconMap[action] || 'fas fa-info-circle'
    },
    
    // 添加格式化操作文本的方法
    formatActionText(action, resourceType) {
      const actionMap = {
        'create': '创建了',
        'update': '更新了',
        'delete': '删除了',
        'login': '登录了系统',
        'logout': '退出了系统',
        'view': '查看了',
        'export': '导出了数据',
        'import': '导入了数据',
        'clear': '清空了数据'
      }
      
      const resourceMap = {
        'course': '笔记',
        'videoCourse': '视频课程',
        'task': '任务',
        'user': '用户信息'
      }
      
      const actionText = actionMap[action] || action
      const resourceText = resourceType ? (resourceMap[resourceType] || resourceType) : ''
      
      return resourceText ? `${actionText}${resourceText}` : actionText
    }
  }
}
</script>

<style scoped>
.profile-app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8fafc;
}

/* Breadcrumb Navigation */
.breadcrumb-nav {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0.75rem 0;
}

.breadcrumb-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: inherit;
  text-decoration: none;
}

.breadcrumb-item:hover {
  color: #3b82f6;
}

.breadcrumb-item:not(:last-child)::after {
  content: '/';
  margin-left: 0.5rem;
  color: #cbd5e1;
}

/* Main Content */
.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: 2rem;
}

.profile-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* Profile Header */
.profile-header {
  display: flex;
  align-items: center;
  gap: 2rem;
  padding: 2rem;
  border-bottom: 1px solid #e2e8f0;
}

.profile-avatar {
  font-size: 80px;
  color: #cbd5e1;
  position: relative;
}

.avatar-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.profile-info h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.profile-info p {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 1.5rem;
}

.profile-stats {
  display: flex;
  gap: 2rem;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.25rem;
}

.stat-label {
  font-size: 11px;
  color: #64748b;
}

/* Profile Sections */
.profile-sections {
  padding: 2rem;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 2rem;
}

.profile-section {
  background: #f8fafc;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.profile-section h3 {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 1rem;
}

/* Activity List */
.activity-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 5px;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
}

.activity-icon {
  width: 32px;
  height: 32px;
  background: #e2e8f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #64748b;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 12px;
  color: #1e293b;
  margin-bottom: 0.25rem;
}

.activity-time {
  font-size: 11px;
  color: #94a3b8;
}

.empty-activity {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #94a3b8;
  font-size: 12px;
  justify-content: center;
  padding: 2rem 0;
}

/* Progress Overview */
.progress-overview {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.progress-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.progress-header span:first-child {
  color: #1e293b;
  font-weight: 500;
}

.progress-header span:last-child {
  color: #64748b;
  font-weight: 600;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e2e8f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #8b5cf6);
  transition: width 0.3s ease;
}

/* Settings List */
.settings-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: white;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.setting-info h4 {
  font-size: 12px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.25rem;
}

.setting-info p {
  font-size: 11px;
  color: #64748b;
  margin: 0;
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  border: 1px solid transparent;
}

.btn-outline {
  background: transparent;
  color: #64748b;
  border-color: #e2e8f0;
}

.btn-outline:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

.btn-danger {
  background: #ef4444;
  color: white;
  border-color: #ef4444;
}

.btn-danger:hover {
  background: #dc2626;
  border-color: #dc2626;
}

/* Avatar Upload Styles */
.avatar-upload-group {
  margin-bottom: 1.5rem;
}

.avatar-upload-container {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.avatar-preview {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  background: #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  font-size: 30px;
  color: #94a3b8;
}

.avatar-upload-controls {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.avatar-file-input {
  display: none;
}

@media (max-width: 768px) {
  .main-content {
    padding: 1rem;
  }
  
  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .profile-sections {
    grid-template-columns: 1fr;
    padding: 1rem;
  }
  
  .setting-item {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .avatar-upload-container {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>